<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 返回按钮 -->
      <view class="back-btn" @tap="goBack">
        <text class="back-icon">←</text>
      </view>

      <!-- Logo -->
      <view class="logo-wrapper">
        <image class="logo-image" src="@/static/logo.png" mode="aspectFill"></image>
      </view>

      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 标题 -->
        <view class="form-title-wrapper">
          <text class="form-title">欢迎注册账户</text>
          <view class="title-underline"></view>
        </view>

        <!-- 用户名输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ 'error': errors.username }">
            <text class="input-icon">👤</text>
            <input 
              class="input-field"
              type="text"
              v-model="username"
              placeholder="请输入用户名（3-20位字符）"
              placeholder-class="input-placeholder"
              maxlength="20"
              @blur="validateUsername"
            />
            <text 
              v-if="username" 
              class="clear-icon" 
              @tap="clearUsername"
            >✕</text>
          </view>
          <text v-if="errors.username" class="error-message">{{ errors.username }}</text>
        </view>

        <!-- 昵称输入 -->
        <view class="input-wrapper">
          <text class="input-icon">✨</text>
          <input 
            class="input-field"
            type="text"
            v-model="nickname"
            placeholder="请输入昵称（选填）"
            placeholder-class="input-placeholder"
            maxlength="20"
          />
          <text 
            v-if="nickname" 
            class="clear-icon" 
            @tap="clearNickname"
          >✕</text>
        </view>

        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ 'error': errors.phone }">
            <text class="input-icon">📱</text>
            <input 
              class="input-field"
              type="number"
              v-model="phone"
              placeholder="请输入手机号"
              placeholder-class="input-placeholder"
              maxlength="11"
              @blur="validatePhone"
            />
            <text 
              v-if="phone" 
              class="clear-icon" 
              @tap="clearPhone"
            >✕</text>
          </view>
          <text v-if="errors.phone" class="error-message">{{ errors.phone }}</text>
        </view>
		
		<!-- 邮箱 -->
		<view class="input-group">
		  <view class="input-wrapper" :class="{ 'error': errors.email }">
		    <text class="input-icon">📧</text>
		    <input 
		      class="input-field"
		      type="text"
		      v-model="email"
		      placeholder="请输入邮箱"
		      placeholder-class="input-placeholder"
		      @blur="validateEmail"
		    />
		    <text 
		      v-if="email" 
		      class="clear-icon" 
		      @tap="clearEmail"
		    >✕</text>
		  </view>
		  <text v-if="errors.email" class="error-message">{{ errors.email }}</text>
		</view>

        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ 'error': errors.password }">
            <text class="input-icon">🔒</text>
            <input 
              class="input-field"
              :type="showPassword ? 'text' : 'password'"
              v-model="password"
              placeholder="请输入密码（6-20位字符）"
              placeholder-class="input-placeholder"
              maxlength="20"
              :password="showPassword"
              @blur="validatePassword"
            />
            <text 
              class="eye-icon" 
              @tap="togglePassword"
            >{{ showPassword ? '👁' : '👁‍🗨' }}</text>
          </view>
          <text v-if="errors.password" class="error-message">{{ errors.password }}</text>
        </view>

        <!-- 确认密码输入 -->
        <view class="input-group">
          <view class="input-wrapper" :class="{ 'error': errors.confirmPassword }">
            <text class="input-icon">🔒</text>
            <input 
              class="input-field"
              :type="showConfirmPassword ? 'text' : 'password'"
              v-model="confirmPassword"
              placeholder="请再次输入密码"
              placeholder-class="input-placeholder"
              maxlength="20"
              :password="showConfirmPassword"
              @blur="validateConfirmPassword"
            />
            <text 
              class="eye-icon" 
              @tap="toggleConfirmPassword"
            >{{ showConfirmPassword ? '👁' : '👁‍🗨' }}</text>
          </view>
          <text v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</text>
        </view>

        <!-- 协议 -->
        <view class="agreement">
          <view class="checkbox-wrapper" @tap="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreedTerms }">
              <text v-if="agreedTerms" class="check-icon">✓</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @tap.stop="viewTerms('user')">《用户协议》</text>
              和
              <text class="link" @tap.stop="viewTerms('privacy')">《隐私政策》</text>
            </text>
          </view>
        </view>

        <!-- 注册按钮 -->
        <button 
          class="register-btn"
          :class="{ disabled: !canRegister }"
		  :disabled="!canRegister"
          @tap="onRegister"
        >
          <text class="register-btn-text">注册</text>
        </button>

        <!-- 登录提示 -->
        <view class="login-tip">
          <text class="tip-text">已有账号？</text>
          <text class="login-link" @tap="goToLogin">立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { register, sendSmsCode,accountLogin } from '@/api/auth'
import { useUser } from '@/composables/useUser'

// 获取用户状态管理
const { setLoginInfo } = useUser()

// 表单数据
const username = ref('')
const nickname = ref('')
const phone = ref('')
const password = ref('')
const email = ref('')
const confirmPassword = ref('')
const agreedTerms = ref(false)
const codeCountdown = ref(0)
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 错误提示
const errors = ref({
  username: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 是否可以注册
const canRegister = computed(() => {
  return username.value.length >= 3 && 
         phone.value.length === 11 && 
         email.value && 
         password.value.length >= 6 &&
         confirmPassword.value.length >= 6 &&
         password.value === confirmPassword.value &&
         agreedTerms.value &&
         !errors.value.username &&
         !errors.value.phone &&
         !errors.value.email &&
         !errors.value.password &&
         !errors.value.confirmPassword
})

/**
 * 用户注册
 */
const onRegister = async () => {
  // 验证所有字段
  const isUsernameValid = validateUsername()
  const isPhoneValid = validatePhone()
  const isEmailValid = validateEmail()
  const isPasswordValid = validatePassword()
  const isConfirmPasswordValid = validateConfirmPassword()

  if (!isUsernameValid || !isPhoneValid || !isEmailValid || !isPasswordValid || !isConfirmPasswordValid) {
    uni.showToast({
      title: '请检查输入信息',
      icon: 'none'
    })
    return
  }

  if (!agreedTerms.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私政策',
      icon: 'none'
    })
    return
  }

  try {
    // 调用后端注册接口
     await register({
      username: username.value,
      phone: phone.value,
      password: password.value,
	  email:email.value,
      nickname: nickname.value || undefined
    })
	// 调用后端登录接口
	const resLogin = await accountLogin({
	  account: username.value,
	  password: password.value
	})
    // 保存用户信息和 Token
    setLoginInfo(resLogin.user, resLogin.accessToken)

    // 提示成功并跳转
    uni.showToast({
      title: '注册成功',
      icon: 'success'
    })

    setTimeout(() => {
      uni.switchTab({
        url: '/pages/home/home'
      })
    }, 1500)

  } catch (error: any) {
    console.error('注册失败:', error)
    // 错误提示已在 request 中处理
  }
}

/**
 * 发送验证码
 */
const sendVerifyCode = async () => {
  // 验证手机号格式
  if (phone.value.length !== 11) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  // 验证手机号是否为纯数字
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }

  try {
    // 调用后端接口发送验证码
    await sendSmsCode(phone.value)

    uni.showToast({
      title: '验证码已发送',
      icon: 'success'
    })

    // 开始倒计时
    codeCountdown.value = 60
    const timer = setInterval(() => {
      codeCountdown.value--
      if (codeCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)

  } catch (error: any) {
    console.error('发送验证码失败:', error)
    // 错误提示已在 request 中处理
  }
}

/**
 * 验证用户名
 */
const validateUsername = () => {
  if (!username.value) {
    errors.value.username = '请输入用户名'
    return false
  }
  if (username.value.length < 3) {
    errors.value.username = '用户名至少需要3个字符'
    return false
  }
  if (username.value.length > 20) {
    errors.value.username = '用户名不能超过20个字符'
    return false
  }
  // 验证用户名格式（只能包含字母、数字、下划线）
  if (!/^[a-zA-Z0-9_]+$/.test(username.value)) {
    errors.value.username = '用户名只能包含字母、数字和下划线'
    return false
  }
  errors.value.username = ''
  return true
}

/**
 * 验证手机号
 */
const validatePhone = () => {
  if (!phone.value) {
    errors.value.phone = '请输入手机号'
    return false
  }
  if (phone.value.length !== 11) {
    errors.value.phone = '手机号必须是11位数字'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    errors.value.phone = '请输入正确的手机号格式'
    return false
  }
  errors.value.phone = ''
  return true
}

/**
 * 验证邮箱
 */
const validateEmail = () => {
  if (!email.value) {
    errors.value.email = '请输入邮箱'
    return false
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(email.value)) {
    errors.value.email = '请输入正确的邮箱格式'
    return false
  }
  errors.value.email = ''
  return true
}

/**
 * 验证密码
 */
const validatePassword = () => {
  if (!password.value) {
    errors.value.password = '请输入密码'
    return false
  }
  if (password.value.length < 6) {
    errors.value.password = '密码至少需要6个字符'
    return false
  }
  if (password.value.length > 20) {
    errors.value.password = '密码不能超过20个字符'
    return false
  }
  errors.value.password = ''
  // 如果确认密码已输入，重新验证确认密码
  if (confirmPassword.value) {
    validateConfirmPassword()
  }
  return true
}

/**
 * 验证确认密码
 */
const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    errors.value.confirmPassword = '请再次输入密码'
    return false
  }
  if (confirmPassword.value !== password.value) {
    errors.value.confirmPassword = '两次输入的密码不一致'
    return false
  }
  errors.value.confirmPassword = ''
  return true
}

/**
 * 清除输入框
 */
const clearUsername = () => {
  username.value = ''
  errors.value.username = ''
}

const clearNickname = () => {
  nickname.value = ''
}

const clearPhone = () => {
  phone.value = ''
  errors.value.phone = ''
}

const clearEmail = () => {
  email.value = ''
  errors.value.email = ''
}

/**
 * 切换密码显示/隐藏
 */
const togglePassword = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value
  console.log('showConfirmPassword',showConfirmPassword.value)
}

/**
 * 切换协议同意状态
 */
const toggleAgreement = () => {
  agreedTerms.value = !agreedTerms.value
}

/**
 * 查看协议
 */
const viewTerms = (type: string) => {
  uni.showToast({
    title: `查看${type === 'user' ? '用户协议' : '隐私政策'}`,
    icon: 'none'
  })
}

/**
 * 返回上一页
 */
const goBack = () => {
  uni.navigateBack()
}

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  uni.redirectTo({
    url: '/pages/accountLogin/accountLogin'
  })
}
</script>

<style scoped>
.register-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
}

.circle-1 {
  width: 400rpx;
  height: 400rpx;
  top: -100rpx;
  right: -100rpx;
}

.circle-2 {
  width: 300rpx;
  height: 300rpx;
  bottom: 100rpx;
  left: -50rpx;
}

.circle-3 {
  width: 200rpx;
  height: 200rpx;
  top: 50%;
  right: 50rpx;
}

/* 内容区域 */
.content-wrapper {
  position: relative;
  z-index: 1;
  height: 100vh;
  padding: 0 50rpx;
  padding-top: calc(var(--status-bar-height) + 120rpx);
  padding-bottom: 40rpx;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  overflow: hidden;
}

/* 返回按钮 */
.back-btn {
  position: absolute;
  top: calc(var(--status-bar-height) + 16rpx);
  left: 32rpx;
  width: 64rpx;
  height: 64rpx;
  background: rgba(255, 255, 255, 0.25);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
  z-index: 10;
  transition: all 0.3s ease;
}

.back-btn:active {
  transform: scale(0.95);
  background: rgba(255, 255, 255, 0.35);
}

.back-icon {
  font-size: 36rpx;
  color: #fff;
  font-weight: bold;
}

/* Logo */
.logo-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 32rpx;
}

.logo-image {
  width: 180rpx;
  height: 180rpx;
  border-radius: 32rpx;
  background: rgba(255, 255, 255, 0.98);
  padding: 0;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

/* 注册表单 */
.register-form {
  background: rgba(255, 255, 255, 0.98);
  border-radius: 28rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 16rpx 64rpx rgba(0, 0, 0, 0.12);
  max-height: 78vh;
  overflow-y: auto;
  backdrop-filter: blur(10rpx);
}

/* 表单标题 */
.form-title-wrapper {
  text-align: center;
  margin-bottom: 36rpx;
}

.form-title {
  font-size: 40rpx;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  letter-spacing: 4rpx;
  position: relative;
  display: inline-block;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
}

.title-underline {
  width: 120rpx;
  height: 6rpx;
  background: linear-gradient(90deg, transparent, #667eea, #764ba2, transparent);
  margin: 16rpx auto 0;
  border-radius: 3rpx;
  animation: underlineShine 2s ease-in-out infinite;
}

@keyframes underlineShine {
  0%, 100% {
    opacity: 0.6;
    transform: scaleX(1);
  }
  50% {
    opacity: 1;
    transform: scaleX(1.1);
  }
}

/* 输入框组 */
.input-group {
  margin-bottom: 20rpx;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  height: 88rpx;
  background: #f8f8f8;
  border-radius: 12rpx;
  padding: 0 20rpx;
  gap: 12rpx;
  transition: all 0.3s ease;
}

.input-wrapper:focus-within {
  background: #f0f0f0;
  box-shadow: 0 0 0 2rpx rgba(102, 126, 234, 0.2);
}

.input-wrapper.error {
  background: #fff5f5;
  box-shadow: 0 0 0 2rpx rgba(231, 76, 60, 0.2);
}

.input-wrapper.error:focus-within {
  background: #ffeaea;
  box-shadow: 0 0 0 2rpx rgba(231, 76, 60, 0.3);
}

/* 错误提示 */
.error-message {
  display: block;
  font-size: 22rpx;
  color: #E74C3C;
  margin-top: 8rpx;
  margin-left: 4rpx;
  line-height: 1.4;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-4rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.input-icon {
  font-size: 32rpx;
  flex-shrink: 0;
  opacity: 0.7;
}

.input-field {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  height: 100%;
}

.input-placeholder {
  color: #aaa;
  font-size: 26rpx;
}

.clear-icon,
.eye-icon {
  font-size: 28rpx;
  color: #999;
  flex-shrink: 0;
  padding: 8rpx;
  transition: opacity 0.2s;
}

.clear-icon:active,
.eye-icon:active {
  opacity: 0.6;
}

.code-btn {
  padding: 12rpx 24rpx;
  background: transparent;
  border: 1rpx solid #4A90E2;
  border-radius: 8rpx;
  font-size: 24rpx;
  flex-shrink: 0;
}

.code-btn::after {
  border: none;
}

.code-btn[disabled] {
  opacity: 0.5;
}

.code-text {
  color: #4A90E2;
  font-size: 24rpx;
  white-space: nowrap;
}

/* 协议 */
.agreement {
  display: flex;
  justify-content: center;
  margin-bottom: 28rpx;
  margin-top: 8rpx;
}

.checkbox-wrapper {
  display: flex;
  align-items: flex-start;
  gap: 10rpx;
}

.checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #ddd;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 2rpx;
  transition: all 0.2s ease;
}

.checkbox.checked {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
}

.check-icon {
  font-size: 18rpx;
  color: #fff;
  font-weight: bold;
}

.agreement-text {
  font-size: 23rpx;
  color: #666;
  line-height: 1.6;
}

.link {
  color: #667eea;
  font-weight: 500;
}

/* 注册按钮 */
.register-btn {
  width: 100%;
  height: 92rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 46rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 28rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.35);
  transition: all 0.3s ease;
}

.register-btn::after {
  border: none;
}

.register-btn:active:not([disabled]) {
  transform: translateY(2rpx);
  box-shadow: 0 6rpx 18rpx rgba(102, 126, 234, 0.3);
}

.register-btn.disabled {
  opacity: 0.5;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.2);
}

.register-btn-text {
  font-size: 30rpx;
  font-weight: 600;
  color: #fff;
  letter-spacing: 2rpx;
}

/* 登录提示 */
.login-tip {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8rpx;
  padding-bottom: 8rpx;
}

.tip-text {
  font-size: 26rpx;
  color: #888;
}

.login-link {
  font-size: 26rpx;
  color: #667eea;
  font-weight: 600;
}
</style>

